<template>
  <div class="app-container">
    <div class="container">
      <!--工具栏-->
      <div>
        <el-form ref="query" :inline="true" :model="query" size="small" class="demo-form-inline">
          <el-form-item label="订单编号：" prop="order_no">
            <el-input v-model="query.order_no" clearable placeholder="订单编号" style="width: 180px;" class="filter-item" @keyup.enter.native="toQuery"/>
          </el-form-item>
          <el-form-item label="产品名称：" prop="commodity_name">
            <el-input v-model="query.commodity_name" clearable placeholder="产品名称" style="width: 180px;" class="filter-item" @keyup.enter.native="toQuery"/>
          </el-form-item>
          <el-form-item label="客户姓名：" prop="user_name">
            <el-input v-model="query.user_name" clearable placeholder="客户姓名" style="width: 180px;" class="filter-item" @keyup.enter.native="toQuery"/>
          </el-form-item>
          <el-form-item label="订单状态：" prop="status">
            <el-select v-model="query.state" clearable placeholder="请选择" class="filter-item" style="width: 180px">
              <el-option v-for="item in orderStatus" :key="item.key" :label="item.value" :value="item.key"/>
            </el-select>
          </el-form-item>
          <el-form-item label="产品分类：" prop="variety_id">
            <el-cascader
              v-model="query.variety_id"
              :options="varietyList"
              :props="{ checkStrictly: true }"
              clearable/>
          </el-form-item>
          <el-form-item label="订单日期：" prop="create_date">
            <el-date-picker
              v-model="query.create_date"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
              style="width:360px"/>
          </el-form-item>
          <el-form-item>
            <el-button size="mini" type="success" icon="el-icon-search" @click="toQuery">搜索</el-button>
            <el-button size="mini" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 按钮 -->
      <div style="display: flex;float: right;margin: 12px 0 15px;">
        <!-- 导出 -->
        <el-button :loading="downloadLoading" :disabled="$refs.table && $refs.table.selection.length === 0" size="mini" class="filter-item" type="warning" icon="el-icon-download" @click="isDownLoad(null, 2)">勾选导出</el-button>
        <el-button :loading="downloadLoading" size="mini" class="filter-item" type="warning" icon="el-icon-download" @click="isDownLoad(false, 1)">查询导出</el-button>
        <el-button :loading="downloadLoading" :disabled="$refs.table && $refs.table.selection.length === 0" size="mini" type="primary" icon="el-icon-s-check" @click="dialog = true">订单审核</el-button>
        <el-button :loading="downloadLoading" :disabled="$refs.table && $refs.table.selection.length === 0" size="mini" type="danger" icon="el-icon-s-promotion" @click="transport">发货(已发出兑换码)</el-button>
      </div>
      <!--表格渲染-->
      <el-table
        v-loading="loading"
        ref="table"
        :data="data"
        :default-expand-all="true"
        size="small"
        tooltip-effect="dark"
        @selection-change="handleSelectionChange">
        <!-- 表头 -->
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column label="产品">
          <template slot-scope="scope">
            <el-row class="right">
              <el-col><div class="grid-content bg-purple" style="font-weight: 700;">订单编号：</div></el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="单价">
          <template slot-scope="scope">
            <el-row style="width:100%;" class="left">
              <el-col :span="24">{{ scope.row.order_no }}</el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="昵称" width="250px">
          <template slot-scope="scope">
            <div class="grid-content bg-purple" style="float:left;font-weight: 700;">订单日期：</div>
            <div>{{ scope.row.create_date }}</div>
          </template>
        </el-table-column>
        <el-table-column label="客户姓名" width="250px"/>
        <el-table-column label="订单总价"/>
        <el-table-column label="充值账号"/>
        <el-table-column label="订单状态"/>
        <el-table-column label="操作" align="center" width="200px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-view" @click="showDetail(scope.row.order_no)">详情</el-button>
            <el-button size="mini" type="primary" icon="el-icon-edit-outline" @click="addRemark(scope.row.order_no)">备注</el-button>
          </template>
        </el-table-column>
        <!-- 下拉内容 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-table :data="scope.row.orderItemList" :show-header="false" style="width: 100%;" size="small">
              <!-- 产品名称 -->
              <el-table-column>
                <template slot-scope="scope">
                  <div style="display:flex;align-items:center">
                    <div style="margin-right: 10px">
                      <el-avatar :size="60" :src="scope.row.cover_url" shape="square"/>
                    </div>
                    <div :title="scope.row.commodity_name" style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis;">{{ scope.row.commodity_name }}</div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="vip_price"/>
              <el-table-column prop="nickname"/>
              <el-table-column prop="user_name"/>
              <el-table-column prop="amount"/>
              <el-table-column prop="account_number"/>
              <el-table-column prop="state">
                <template slot-scope="scope">
                  <span>{{ pointsOrder[scope.row.state] }}</span>
                </template>
              </el-table-column>
              <el-table-column />
            </el-table>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <el-pagination
        :total="total"
        :current-page="page + 1"
        background
        style="margin-top: 8px;"
        layout="total, prev, pager, next, sizes"
        @size-change="sizeChange"
        @current-change="pageChange"/>
    </div>
    <el-dialog :visible.sync="dialogFormVisible" title="导出查询">
      <span> 温馨提示：已检索到订单{{ currentTatol }}条，需要分{{ currentpage }}批导出，每次导出8000条！
      点击下载即可下载当前批数订单，点击完成后请耐心等待下载完成！ </span>
      <span>选择导出下载：第</span>
      <el-select v-model="currentpage">
        <el-option
          v-for="(item, index) in dpage"
          :key="item"
          :label="index +1 "
          :value="item"/>
      </el-select>
      <span>批</span>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dowSelectExcel(true)">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialog" title="订单审核" width="500px">
      <el-form ref="form" :model="staeForm" size="small" label-width="120px">
        <el-form-item label="审核结果:" prop="member_type">
          <el-radio-group v-model="staeForm.state">
            <el-radio v-for="item in updatePointsOrder" :key="item.key" :label="item.key">{{ item.value }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="loading" type="primary" @click="dialog = false">取消</el-button>
        <el-button :loading="loading" type="primary" @click="audit">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import initData from '@/mixins/initData'
import COMMEN from '@/utils/commen'
import * as order from '@/api/erp/order'
import { downLoadExcel } from '@/utils/index'
import { getCascadeVarietyList } from '@/api/mall/commodity'
// import { downloadFile } from '@/utils/index'

export default {
  mixins: [initData],
  data() {
    return {
      pickerOptions: COMMEN.PICKEROPTIONS,
      orderStatus: COMMEN.STATUS_POINTS_ORDER,
      pointsOrder: COMMEN.POINTS_ORDER,
      updatePointsOrder: COMMEN.STATUS_UPDATE_POINTS_ORDER,
      varietyList: [],
      query: {},
      multipleSelection: [], // 勾选的数据列表
      downloadLoading: false,
      dialogFormVisible: false,
      currentTatol: '',
      dialog: false,
      currentpage: '',
      staeForm: {}
    }
  },
  computed: {
    dpage() {
      return Math.ceil(this.currentTatol / 8000)
    }
  },
  created() {
    // 获取员工列表
    this.$nextTick(() => {
      this.init()
    })
    // 获取商品分类
    getCascadeVarietyList().then(res => {
      this.varietyList = res.content
    })
  },
  methods: {
    beforeInit() {
      this.url = 'order/order-list'
      this.params = { page: this.page, size: this.size, order_type: '1' }
      // 查询条件组装
      this.getParam()
      return true
    },
    // 获得检索条件
    getParam() {
      const query = this.query
      const order_no = query.order_no // 订单编号
      const commodity_name = query.commodity_name // 产品名称
      const user_name = query.user_name // 客户姓名
      const state = query.state // 订单状态
      const variety_id = query.variety_id // 产品分类
      const create_date = query.create_date // 订单日期
      if (order_no) {
        this.params['order_no'] = order_no
      }
      if (commodity_name) {
        this.params['commodity_name'] = commodity_name
      }
      if (user_name) {
        this.params['user_name'] = user_name
      }
      if (state !== '') {
        this.params['state'] = state
      }
      if (variety_id) {
        this.params['variety_id'] = variety_id.join(',')
      }
      if (create_date !== '' && create_date !== undefined) {
        this.params['create_date'] = create_date.join('~')
      }
    },
    showDetail(order_no) {
      this.$router.push(
        {
          path: '/order/pointsOrder',
          query: { order_no: order_no }
        })
    },
    addRemark(order_no) {
      this.$prompt('', '订单备注', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'textarea'
      }).then(({ value }) => {
        const data = {
          order_no: order_no,
          remark: value
        }
        order.updateOrder(data).then(res => {
          var state = res ? '成功！' : '失败！'
          this.$notify({
            title: state,
            message: '修改' + state,
            type: res ? 'success' : 'error'
          })
          this.init()
        })
      })
    },
    // 订单审核
    audit() {
      const param = {
        order_no: this.multipleSelection.join(','),
        state: this.staeForm.state
      }
      order.updateOrder(param).then(res => {
        var state = res ? '成功！' : '失败！'
        this.$notify({
          title: state,
          message: '修改' + state,
          type: res ? 'success' : 'error'
        })
        this.dialog = false
        this.init()
      })
    },
    // 订单发货
    transport() {
      this.$confirm('确定要发货吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const param = {
          order_no: this.multipleSelection.join(','),
          state: 54 // 已收到
        }
        order.updateOrder(param).then(res => {
          var state = res ? '成功！' : '失败！'
          this.$notify({
            title: state,
            message: '发货' + state,
            type: res ? 'success' : 'error'
          })
          this.init()
        })
      })
    },
    resetQuery() {
      // 重置筛选框
      this.query.order_no = '' // 订单编号
      this.query.commodity_name = '' // 产品名称
      this.query.user_name = '' // 客户姓名
      this.query.team_name = '' // 所属团队
      this.query.state = '' // 订单状态
      this.query.variety_id = '' // 产品分类
      this.query.recommend_name = '' // 邀请人
      this.query.create_date = '' // 订单日期
      // 重新请求数据
      this.init()
    },
    // 导出校验
    // type = 1：查询导出 2：勾选导出
    isDownLoad(isDirectExport, type) {
      if (type === 2 && this.multipleSelection.length <= 0) {
        this.$notify({
          title: '当前没有勾选，请勾选',
          type: 'success',
          duration: 2500
        })
      } else {
        this.$confirm('导出订单数量较多的时候，请耐心等待数据组装完成！', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '正在进行帮您导出，文件过多时请耐心等待!'
          })
          if (type === 1) {
            this.dowSelectExcel(isDirectExport)
          } else {
            this.downloadExcel()
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      }
    },
    // 查询导出
    dowSelectExcel(isDirectExport) {
      const param = this.params
      this.getParam()
      if (isDirectExport) {
        param.curpage = this.currentpage - 1 // 直接执行导出
        order.queryDownload(param).then(res => {
          downLoadExcel(res, '订单.xls')
          this.$notify({
            title: '导出成功，请耐心等待',
            type: 'success',
            duration: 2500
          })
        })
      } else {
        // 先发请求那total
        order.getLisyCount(param).then(res => {
          this.currentTatol = res
          if (res === 0) {
            this.$notify({
              title: '当前查询条件无导出数据',
              type: 'success',
              duration: 2500
            })
          } else if (this.currentTatol > 8000) { // 先分页展示
            this.dialogFormVisible = true
          } else { // 直接执行导出
            order.queryDownload(param).then(res => {
              downLoadExcel(res, '订单.xls')
              this.$notify({
                title: '导出成功，请耐心等待',
                type: 'success',
                duration: 2500
              })
            })
          }
        })
      }
    },
    // 勾选导出
    downloadExcel() {
      const param = {
        order_no: this.multipleSelection.join(','),
        order_type: 1
      }
      order.pickDownload(param).then(res => {
        downLoadExcel(res, '订单列表.xls')
        this.$notify({
          title: '导出成功，请耐心等待',
          type: 'success',
          duration: 2500
        })
      })
    },
    // 将勾选的数据存到列表中
    handleSelectionChange(val) {
      console.log(val)
      const array = []
      val.forEach(item => {
        array.push(item.order_no)
      })
      this.multipleSelection = array
    },
    click() {
      order.addOrder()
    }
  }
}
</script>

<style>
  .left {
    text-align: left;
    width: max-content;
  }
  .right {
    text-align: right;
  }
  .el-table__body-wrapper {
    min-height: 50px !important;
  }
</style>

